package cn.hchaojie.web.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DemoJdbc {
	public static void main(String[] args) {
		// 加载驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// 连接数据库
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "root");
			
			// 发送sql语句
			ps = connection.prepareStatement("select count(*) from employees");
			rs = ps.executeQuery();
			
			// 处理结果
			if (rs.next()) {
				int count = rs.getInt(1);		// 从1开始的
				System.out.println("员工总记录数：" + count);
			}
			
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			closeQuietly(rs);
			closeQuietly(ps);
			closeQuietly(connection);
		}
	}
	
	private static void closeQuietly(AutoCloseable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
